package cn.car.service.impl;

import cn.car.domains.bo.QueryUserBo;
import cn.car.domains.entity.SysUserEntity;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.SysUserMapper;
import cn.car.service.SysUserService;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 新增用户
     * 自动填充创建时间，添加事务支持
     */
    @Override
    public Long addUser(SysUserEntity user) {

        // 执行插入操作
        int rows;
        try {
            rows = sysUserMapper.insertUser(user);
        } catch (DuplicateKeyException e) {
            throw CarAccessControlException.USER_EXIST;
        }

        if (rows != 1) {
            throw CarAccessControlException.INSERT_ERROR.newInstance("插入用户失败");
        }
        return user.getId();
    }

    /**
     * 根据ID查询用户
     */
    @Override
    public SysUserEntity getUserById(Long id) {
        if (id == null) {
            return null;
        }
        return sysUserMapper.selectById(id);
    }

    /**
     * 根据用户名查询用户
     */
    @Override
    public SysUserEntity getUserByUsername(String username) {
        if (StrUtil.isEmpty(username)) {
            return null;
        }
        return sysUserMapper.selectByUsername(username);
    }

    /**
     * 更新用户信息
     */
    @Override
    public void updateUser(SysUserEntity user) {
        // 校验ID是否存在
        if (user.getId() == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("查询id不能为空");
        }

        // 执行更新操作
        int rows = sysUserMapper.updateUser(user);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    /**
     * 根据ID删除用户
     */
    @Override
    public void deleteUser(Long id) {
        // 校验ID是否存在
        if (id == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("删除id不能为空");
        }

        // 执行删除操作
        int rows = sysUserMapper.deleteById(id);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    /**
     * 分页查询用户信息
     */
    @Override
    public List<SysUserEntity> list(QueryUserBo queryUserBo) {
        return sysUserMapper.selectUserList(queryUserBo);
    }
}
